package com.emar.adx.yiqifa.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by xiaoliang on 2014/12/3 10:25.
 */
public class DateUtil {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //字符串转化为日期
    public static Date stringToDate(String date,String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date d = new Date();
        try{
            d = sdf.parse(date);
        }catch (Exception e){

        }
        return d;
    }
    //日期转化为字符串
    public static String dateToString(Date date,String pattern){
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }
    
    /**
     * 获取两个时间相差的月数
     * @param date1
     * @param date2
     * @return
     * @throws ParseException
     */
    public static int getMonthSpace(Date date1, Date date2){  
		int iMonth = 0;
		int flag = 0;
		try {
			Calendar objCalendarDate1 = Calendar.getInstance();
			objCalendarDate1.setTime(date1);

			Calendar objCalendarDate2 = Calendar.getInstance();
			objCalendarDate2.setTime(date2);

			if (objCalendarDate2.equals(objCalendarDate1))
				return 0;
			if (objCalendarDate1.after(objCalendarDate2)) {
				Calendar temp = objCalendarDate1;
				objCalendarDate1 = objCalendarDate2;
				objCalendarDate2 = temp;
			}
			if (objCalendarDate2.get(Calendar.DAY_OF_MONTH) < objCalendarDate1
					.get(Calendar.DAY_OF_MONTH))
				flag = 1;

			if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1
					.get(Calendar.YEAR))
				iMonth = ((objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1
						.get(Calendar.YEAR))
						* 12
						+ objCalendarDate2.get(Calendar.MONTH) - flag)
						- objCalendarDate1.get(Calendar.MONTH);
			else
				iMonth = objCalendarDate2.get(Calendar.MONTH)
						- objCalendarDate1.get(Calendar.MONTH) - flag;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return iMonth;
	}

    /**
     * 给定日期和格式    获取转化后的日期
     * @param date
     * @param pattern
     * @return
     */
    public static Date getDate(Date date,String pattern){
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String s = sdf.format(date);
        try{
            d = sdf.parse(s);
        }catch (Exception e){

        }
        return d;
    }

    /**
     * 获取月表
     * @param date yyyy-MM-dd
     * @return
     */
    public static int getMonthTable(String date){
        String[] s = date.split("-");
        String y = s[0];
        String m = s[1];
        String d = s[2];

        String temp = y+m;

        String ss = temp.substring(2);

        return Integer.parseInt(ss);
    }
    /**
     * 得到两个时间相差的天数
     * @param date
     * @return
     */
    public static long getDaysBetweenTwoDay(Date date1, Date date2) {
		long time1 = date1.getTime();
		long time2 = date2.getTime();
		long days = 0;
		long mod = 0;
		if (time1 > time2) {
			days = 0;
		} else if (time1 < time2) {
			days = (time2 - time1) / (24 * 3600 * 1000);
			mod = (time2 - time1) % (24 * 3600 * 1000);
		} else {
			return 0;
		}
		if (mod > 0) {
			days++;
		}
		return days;
	}
    /**
     * 根据给定的时间，计算出所在的周，获取这个周内的周几是几号
     * @param date
     * @param calendarDayValue
     * @return
     */
    public static Date getDayInWeekByDay(Date date,int calendarDayValue){
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK,calendarDayValue);
        Date d = c.getTime();
        return d;
    }

    /**
     * 获取指定日期所在月的第一天
     * @param date
     * @return
     */
    public static Date getLastDateOfMonthByDay(Date date){
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        return ca.getTime();
    }

    /**
     * 获取指定日期所在月最后一天
     * @param date
     * @return
     */
    public static Date getFirstDateOfMonthByDay(Date date){
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        ca.add(Calendar.MONTH, 0);
        ca.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        return ca.getTime();
    }

    public static List<Date> getDates(Date dBegin, Date dEnd) {
        List<Date> lDate = new ArrayList<Date>();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }
    /**
     * 获取当前时间的前一天
     * @param date
     * @return
     */
    public static Date getPreDay(Date date ){
    	Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
        calendar.add(Calendar.DATE, -1);    //得到前一天
        Date date2 = calendar.getTime();
        return date2;
    }


    public static Date dateAddMinutes(Date date, int minutes) {
        if (date == null)
            return null;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MINUTE, minutes);
        return cal.getTime();
    }

    public static Date dateAddHours(Date date, int hours) {
        if (date == null)
            return null;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, hours);
        return cal.getTime();
    }

    public static Date dateAddDays(Date date, int addDays) {
        if (date == null)
            return null;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, addDays);
        return cal.getTime();
    }

    public static Date dateAddMonths(Date date, int addMonths) {
        if (date == null)
            return null;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, addMonths);
        return cal.getTime();
    }

    public static Date dateAddMonths(Date date, double months) {
        if (date == null)
            return null;
        int addMonths = (int) Math.ceil(months);
        int addDays = (int) Math.round((months - addMonths) * 31);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, addMonths);
        cal.add(Calendar.DATE, addDays);
        return cal.getTime();
    }

    public static Date dateAddYears(Date date, int addYears) {
        if (date == null)
            return null;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.YEAR, addYears);
        return cal.getTime();
    }

    public static boolean isDate(String strDate, String pattern) {
        if (strDate == null || strDate.trim().length() <= 0)
            return false;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            sdf.parse(strDate);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    public static int getIntervalOfDay(Date d1, Date d2) {
        int elapsed = 0;
        boolean isAfter = false;
        Date temp;
        if (d1.after(d2)) {
            temp = d1;
            d1 = d2;
            d2 = temp;
            isAfter = true;
        }

        while (d1.before(d2)) {
            d1 = dateAddDays(d1, 1);
            elapsed++;
        }
        if (isAfter)
            elapsed = 0 - elapsed;
        return elapsed;
    }

    /**
     * Elapsed days based on current time
     *
     * @param date
     *            Date
     *
     * @return int number of days
     */
    public static int getElapsedDays(Date date) {
        return elapsed(date, Calendar.DATE);
    }

    /**
     * Elapsed days based on two Date objects
     *
     * @param d1
     *            Date
     * @param d2
     *            Date
     *
     * @return int number of days
     */
    public static int getElapsedDays(Date d1, Date d2) {
        return elapsed(d1, d2, Calendar.DATE);
    }

    /**
     * Elapsed months based on current time
     *
     * @param date
     *            Date
     *
     * @return int number of months
     */
    public static int getElapsedMonths(Date date) {
        return elapsed(date, Calendar.MONTH);
    }

    /**
     * Elapsed months based on two Date objects
     *
     * @param d1
     *            Date
     * @param d2
     *            Date
     *
     * @return int number of months
     */
    public static int getElapsedMonths(Date d1, Date d2) {
        return elapsed(d1, d2, Calendar.MONTH);
    }

    /**
     * Elapsed years based on current time
     *
     * @param date
     *            Date
     *
     * @return int number of years
     */
    public static int getElapsedYears(Date date) {
        return elapsed(date, Calendar.YEAR);
    }

    /**
     * Elapsed years based on two Date objects
     *
     * @param d1
     *            Date
     * @param d2
     *            Date
     *
     * @return int number of years
     */
    public static int getElapsedYears(Date d1, Date d2) {
        return elapsed(d1, d2, Calendar.YEAR);
    }

    /**
     * All elaspsed types
     *
     * @param g1
     *            GregorianCalendar
     * @param g2
     *            GregorianCalendar
     * @param type
     *            int (Calendar.FIELD_NAME)
     *
     * @return int number of elapsed "type"
     */
    private static int elapsed(GregorianCalendar g1, GregorianCalendar g2,
                               int type) {
        GregorianCalendar gc1, gc2;
        int elapsed = 0;
        // Create copies since we will be clearing/adding
        if (g2.after(g1)) {
            gc2 = (GregorianCalendar) g2.clone();
            gc1 = (GregorianCalendar) g1.clone();
        } else {
            gc2 = (GregorianCalendar) g1.clone();
            gc1 = (GregorianCalendar) g2.clone();
        }
        if (type == Calendar.MONTH || type == Calendar.YEAR) {
            gc1.clear(Calendar.DATE);
            gc2.clear(Calendar.DATE);
        }
        if (type == Calendar.YEAR) {
            gc1.clear(Calendar.MONTH);
            gc2.clear(Calendar.MONTH);
        }
        while (gc1.before(gc2)) {
            gc1.add(type, 1);
            elapsed++;
        }
        return elapsed;
    }

    /**
     * All elaspsed types based on date and current Date
     *
     * @param date
     *            Date
     * @param type
     *            int (Calendar.FIELD_NAME)
     *
     * @return int number of elapsed "type"
     */
    private static int elapsed(Date date, int type) {
        return elapsed(date, new Date(), type);
    }

    /**
     * All elaspsed types
     *
     * @param d1
     *            Date
     * @param d2
     *            Date
     * @param type
     *            int (Calendar.FIELD_NAME)
     *
     * @return int number of elapsed "type"
     */
    private static int elapsed(Date d1, Date d2, int type) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(d1);
        GregorianCalendar g1 = new GregorianCalendar(cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
        cal.setTime(d2);
        GregorianCalendar g2 = new GregorianCalendar(cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
        return elapsed(g1, g2, type);
    }

    public static int getDaysOfMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return getMonthDateCount(cal);
    }

    protected static int getMonthDateCount(Calendar cal) {
        Calendar cal2 = (Calendar) cal.clone();
        cal2.add(Calendar.MONTH, 1);
        cal2.set(Calendar.DAY_OF_MONTH, 1);
        cal2.add(Calendar.DAY_OF_MONTH, -1);
        return cal2.get(Calendar.DAY_OF_MONTH);
    }
}
